import { Component, OnInit, Input } from "@angular/core";
import { UserAuthService } from "src/app/@core/user-auth.service";
import { DialogService } from 'ng-devui/modal';
import { FormLayout, DValidateRules } from "ng-devui/form";
import { Router } from '@angular/router';

@Component({
  selector: "app-user-verification",
  templateUrl: "./user-verification.component.html",
  styleUrls: ["./user-verification.component.scss"],
})
export class UserVerificationComponent implements OnInit {
  @Input() data: any;
  layoutDirection: FormLayout = FormLayout.Vertical;
  constructor(
    private userAuthService: UserAuthService,
    private router: Router,
    private dialogService: DialogService
  ) { }

  ngOnInit(): void { }

  formRules: { [key: string]: DValidateRules } = {
    nameRules: {
      validators: [{ required: true, message: "真实姓名不能为空" }],
      messageShowType: "text",
    },
    idRules: {
      validators: [
        { required: true, message: "身份证号不能为空" },
        { maxlength: 18, message: "长度不能多于18位", priority: 1 },
        {
          pattern:
            /^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$|^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          message: "身份证号不符合规范",
          priority: 0,
        },
      ],
      messageShowType: "text",
    },
  };

  verification = { realName: null, identityNumber: null };

  userId = parseInt(localStorage.getItem("userId"));

  config = {
    id: 'dialog-service',
    width: '360px',
    maxHeight: '200px',
    backdropCloseable: true,
  };

  openDialog(dialogtype?: string, title?: string, text?: string) {
    const results = this.dialogService.open({
      ...this.config,
      title: title,
      content: text,
      dialogtype: dialogtype,
      buttons: [{
        cssClass: 'primary',
        text: '关闭',
        handler: ($event: Event) => {
          results.modalInstance.hide();
          if (dialogtype == "success") {
            this.router.navigate(['/home']);
          }
        }
      }]
    });
  }

  onSubmit({ valid }) {
    if (valid) {
      this.userAuthService
        .userVerification(
          this.userId,
          this.verification.realName,
          this.verification.identityNumber
        )
        .subscribe((res) => {
          if (res.code == 0) {
            this.openDialog("success", '认证成功', res.msg);
          } else {
            this.openDialog("failed", '认证失败', res.msg);
          }
        });
    }
  }
}
